import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class CacheService {
  static const String _cacheKeyPrefix = 'health_app_cache_';
  static const Duration defaultCacheDuration = Duration(hours: 1);

  // 保存数据到缓存
  Future<bool> saveData(String key, dynamic data, {Duration? expiry}) async {
    final prefs = await SharedPreferences.getInstance();
    final cacheItem = {
      'data': data,
      'timestamp': DateTime.now()
          .add(expiry ?? defaultCacheDuration)
          .millisecondsSinceEpoch
    };
    return await prefs.setString('$_cacheKeyPrefix$key', jsonEncode(cacheItem));
  }

  // 从缓存读取数据
  Future<dynamic> getData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    final cachedData = prefs.getString('$_cacheKeyPrefix$key');

    if (cachedData == null) return null;

    final cacheItem = jsonDecode(cachedData);
    final expiryTime = cacheItem['timestamp'];

    if (expiryTime < DateTime.now().millisecondsSinceEpoch) {
      // 缓存已过期
      await prefs.remove('$_cacheKeyPrefix$key');
      return null;
    }

    return cacheItem['data'];
  }

  // 清除指定缓存
  Future<bool> removeData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return await prefs.remove('$_cacheKeyPrefix$key');
  }

  // 清除所有缓存
  Future<bool> clearAll() async {
    final prefs = await SharedPreferences.getInstance();
    final allKeys = prefs.getKeys();
    final cacheKeys = allKeys.where((key) => key.startsWith(_cacheKeyPrefix));

    bool result = true;
    for (final key in cacheKeys) {
      final success = await prefs.remove(key);
      if (!success) result = false;
    }

    return result;
  }
}
